<?php
namespace Admin\Controller;

class MediaController extends Controller {

		

	

	//文本消息列表
	public function text() {
		$data = Db::table('text') -> get();
		View::with('data', $data) -> make();
	}

	//添加文本素材
	public function addText() {
		if (IS_POST) {
			if (Db::table('text') -> insert($_POST)) {
				View::ajax(array('code' => 0, 'message' => '添加成功'));
			} else {
				View::ajax(array('code' => 1, 'message' => '添加失败'));
			}
		} else {
			View::make();
		}
	}

	//图片上传
	public function upload() {
		$file = Upload::type('jpg,png,jpeg,gif') -> make();
		
		
		if ($file) {
			
			$wx = Weixin::instance('material') -> upload('image', $file[0]['path'], 1);

			$data['path'] = $file[0]['path'];
			$data['media_id'] = $wx['media_id'];
			$data['create_at'] = time();

			Db::table('image') -> insert($data);
			View::ajax($data);
		}
	}

	//图片素材
	public function image() {
		$data = Db::table('image') ->orderby('id','desc') -> get();
		View::with('data', $data) -> make();
	}

	//添加文本素材
	public function addImage() {
		if (IS_POST) {
			if (Db::table('image') -> insert($_POST)) {
				View::ajax(array('code' => 0, 'message' => '添加成功'));
			} else {
				View::ajax(array('code' => 1, 'message' => '添加失败'));
			}
		} else {
			View::make();
		}
	}
	
	public function del()
	{
		//$media_id 为素材media_id
		
		$result = Weixin::instance('material')->delete($_POST['media_id']);
		$re = Db::table('image')->where('media_id',$_POST['media_id'])->delete();
		if($result && $re)
		{
			View::ajax(array('code' => 0, 'message' => '删除成功'));
		}
		else
		{
			View::ajax(array('code' => 1, 'message' => '删除失败'));
		}
	}

	//修改图片素材的关键词
	public function changeImageKeyword() {
		if(Db::table('image') -> where('media_id', $_POST['media_id']) -> update($_POST))
		{
			View::ajax(array('code' => 0, 'message' => '关键词设置成功'));
		}
		else
		{
			View::ajax(array('code' => 1, 'message' => '关键词设置失败'));
		}
		
		
	}

}
